package com.gm.manager.module.login.controller;

import com.gm.manager.common.domian.PE;
import com.gm.manager.common.domian.RP;
import com.gm.manager.common.domian.RS;
import com.gm.manager.common.domian.RSD;
import com.gm.manager.common.tools.LoginUtils;
import com.gm.manager.common.tools.ValidatorUtils;
import com.gm.manager.module.login.entity.LoginBack;
import com.gm.manager.module.login.entity.LoginPost;
import com.gm.manager.module.login.entity.UpdatePassword;
import com.gm.manager.module.login.service.LoginService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author zhuZhaoYang
 * @date 2021/8/7 13:59
 */
@RestController
@RequestMapping("/")
@Validated

public class LoginController {

    private DefaultKaptcha defaultKaptcha;
    private LoginService loginService;

    @Autowired
    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    @Autowired
    public void setDefaultKaptcha(DefaultKaptcha defaultKaptcha) {
        this.defaultKaptcha = defaultKaptcha;
    }

    @ApiOperation(value = "验证码")
    @GetMapping(value = "captcha", produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        // 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");

        //-------------------生成验证码 begin --------------------------
        //获取验证码文本内容
        String text = defaultKaptcha.createText();
        System.out.println("验证码内容：" + text);
        //将验证码放入session中
        request.getSession().setAttribute("captcha", text);
        //根据文本内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //输出流输出图片，格式jpg
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //-------------------生成验证码 end ----------------------------
    }


    @ApiOperation("登录")
    @PostMapping("login")
    public RP login(@RequestBody LoginPost loginPost, HttpServletRequest request) {
        //参数校验，对RequestBody使用
        ValidatorUtils.validateEntity(loginPost);
        LoginBack login = loginService.login(loginPost.getUsername(), loginPost.getPassword(), loginPost.getCode(), request);
        if (login == null) {
            return new PE("用户名或密码错误");
        }
        return new RSD(login);
    }

    @ApiOperation("登出")
    @GetMapping("logout")
    public RP logout(@NotBlank(message = "请先登录") @RequestParam String token) {
        LoginBack loginBack = LoginUtils.checkLogin(token);
        int logout = loginService.logout(loginBack.getId());
        if (logout != 1) {
            return new PE("登出失败");
        }
        return new RS();
    }

    @ApiOperation("修改密码")
    @PostMapping("updatePassword")
    public RP updatePassword(@RequestBody UpdatePassword updatePassword) {
        ValidatorUtils.validateEntity(updatePassword);
        LoginBack loginBack = LoginUtils.checkLogin(updatePassword.getToken());
        int success = loginService.updatePassword(updatePassword.getNewPassword(), loginBack.getId(), loginBack.getUsername());
        if (success != 1) {
            return new PE("修改失败");
        }
        return new RS();
    }
}
